package com.fzebu.fastboot.docs;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jack
 * @version 1.0.0
 * @create 2020/2/21 17:20
 */
public class ExcelUtil {

    public static List<List<String>> read(File file) throws IOException {
        return read(file, 0);
    }

    public static List<List<String>> read(File file, int sheetIndex) throws IOException {
        Workbook workbook = checkAndGetWorkbook(file);
        Sheet sheet = getSheet(workbook, sheetIndex);
        return getSheetData(workbook, sheet);
    }

    public static List<List<String>> getSheetData(Workbook workbook, final Sheet sheet) {
        final List<List<String>> list = new ArrayList<>();
        sheet.rowIterator().forEachRemaining(row -> {
            List<String> rowData = getRowData(row);
            if (rowData != null && rowData.size() > 0) {
                list.add(rowData);
            }
        });
        return list;
    }

    public static List<String> getRowData(Row row) {
        int size = row.getLastCellNum();
        if (size == 0) return null;
        List<String> rowData = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            Cell cell = row.getCell(i);
            if (cell != null) {
                CellStyle cellStyle = cell.getCellStyle();
                cell.setCellType(CellType.STRING);
                String value = cell.toString();
                if (StringUtils.isNotEmpty(value)) {
                    rowData.add(value);
                }
            } else {
                rowData.add(null);
            }
        }
        return rowData;
    }

    public static Sheet getSheet(Workbook workbook, int index) {
        return workbook.getSheetAt(index);
    }

    public static Sheet getSheet(Workbook workbook, String name) {
        return workbook.getSheet(name);
    }

    private static Workbook checkAndGetWorkbook(File file) throws IOException {
        if (file == null || !file.exists() || !file.isFile()) {
            throw new IOException("it's not an excel file");
        }
        String fileName = file.getName();
        String ext = StringUtils.substringAfter(fileName, ".");
        FileInputStream fis = new FileInputStream(file);
        if ("xls".equalsIgnoreCase(ext)) {
            HSSFWorkbook sheets = new HSSFWorkbook(fis);
            fis.close();
            return sheets;
        }
        if ("xlsx".equalsIgnoreCase(ext)) {
            XSSFWorkbook sheets = new XSSFWorkbook(fis);
            fis.close();
            return sheets;
        }
        throw new IOException("file extensions invalid");
    }
}
